package com.wechat.service.controller;


import com.wechat.service.config.HttpAPIService;
import com.wechat.service.config.HttpResult;
import com.wechat.service.paramBean.WeiXinValid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhanghl
 */
@Controller
public class CheckController {

    @Resource
    private HttpAPIService httpAPIService;

    @Value("${weixin.gongzhonghao.token}")
    private String token;
    @Value("${getTokenUrl}")
    private String getTokenUrl;
    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.secret}")
    private String secret;
    @Value("${weixin.access.token}")
    private String accessToken;

    /**
     * 验证签名
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String token,String signature, String timestamp, String nonce) {
        // 对token、timestamp、和nonce按字典排序.
        String[] paramArr = new String[] {token, timestamp, nonce};
        Arrays.sort(paramArr);

        // 将排序后的结果拼接成一个字符串.
        String content  = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

        String ciphertext = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            // 对拼接后的字符串进行sha1加密.
            byte[] digest = md.digest(content.toString().getBytes());
            ciphertext = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // 将sha1加密后的字符串与signature进行对比.
        return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false;
    }

    /**
     * 将字节数组转换为十六进制字符串.
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串.
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1' , '2', '3', '4' , '5', '6', '7' , '8', '9', 'A' , 'B', 'C', 'D' , 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }

    @RequestMapping("/hello")
    public @ResponseBody String hello(){
        return "hello";
    }

    @RequestMapping("")
    @ResponseBody
    public Object valid(WeiXinValid param){
        boolean flag = checkSignature(token,param.getSignature(),param.getTimestamp(),param.getNonce());
        if (flag){
            System.out.println("验签成功！");
        }
        System.out.println(param);
        return param.getEchostr();
    }

    /**
     * 获取AccessToken
     * @return
     */
    @RequestMapping("/getAccessToken")
    @ResponseBody
    public Object getAccessToken() throws Exception {
        String url = getTokenUrl + "&appid=" + appid + "&secret=" + secret;
        String str = httpAPIService.doGet(url);
        System.out.println(str);
        return str;
    }

    /**
     * 添加微信客服号
     * @return
     */
    @RequestMapping("/addkefuAccount")
    @ResponseBody
    public Object addkefuAccount() throws Exception {
        String url = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token=" + accessToken;

        Map<String,Object> param = new HashMap<>();
        param.put("kf_account","test1@test");
        param.put( "nickname" , "客服1");
        param.put("password" , "pswmd5");

        HttpResult result = httpAPIService.doPost(url,param);
        System.out.println(result);
        return result;
    }

    @RequestMapping("/httpclient")
    @ResponseBody
    public String test() throws Exception {
        String str = httpAPIService.doGet("http://www.baidu.com");
        System.out.println(str);

        return "hello";
    }

}
